import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login.vue";
import Home from "../views/Home.vue";
import Welcome from "../views/Welcome.vue";
import User from "../views/user/User.vue";
import Rights from "../views/jurisdiction/Rights.vue";
import Roles from "../views/jurisdiction/Roles.vue";
import Goods from "../views/commodity/Goods.vue";
import Params from "../views/commodity/Params.vue";
import Categories from "../views/commodity/Categories.vue";
import Add from "../views/commodity/Add.vue";
import Order from "../views/order/Order.vue";
import Report from "../views/database/Report.vue";

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: Welcome
      },
      {
        path: "/users",
        component: User
      },
      {
        path: "/rights",
        component: Rights
      },
      {
        path: "/roles",
        component: Roles
      },
      {
        path: "/goods",
        component: Goods
      },
      {
        path: "/params",
        component: Params
      },
      {
        path: "/categories",
        component: Categories
      },
      {
        path: "/goods/add",
        component: Add
      },
      {
        path: "/orders",
        component: Order
      },
      {
        path: "/reports",
        component: Report
      }
    ]
  }
];

const router = new VueRouter({
  mode: "history",
  routes
});

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from代表从哪个路径跳转而来
  // next是一个函数，表示放行
  if (to.path === "/login") return next();
  const tokenStr = window.sessionStorage.getItem("token");
  if (!tokenStr) return next("/login");
  next();
});

export default router;
